<template>
  <div>
    <!-- form表单区 -->
    <el-form
      class="login-form"
      label-width="0px"
      :model="loginForm"
      :rules="loginFormRules"
      ref="loginFormRef"
    >
      <!-- 用户名 -->
      <el-form-item prop="username">
        <el-input
          prefix-icon="iconfont icon-user"
          placeholder="请输入用户名"
          v-model="loginForm.username"
        ></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
          prefix-icon="iconfont icon-3702mima"
          placeholder="请输入密码"
          v-model="loginForm.password"
          type="password"
        ></el-input>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item class="btns">
        <el-button type="primary" @click="Login">登录</el-button>
        <el-button type="info" @click="resetForm('loginFormRef')"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getLoginData } from 'network/login'
export default {
  name: 'LoginForm',
  data() {
    return {
      //登录表单的数据绑定对象
      loginForm: {
        username: '',
        password: '',
      },
      // 登录表单的验证规则对象
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 12,
            message: '长度在 8 到 12 个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    resetForm() {
      this.$refs.loginFormRef.resetFields()
    },
    Login() {
      this.$refs.loginFormRef.validate((valid) => {
        if (!valid) return
        // const { data: res } = await this.$http.post('login', this.loginForm)
        this.getLoginData()
      })
    },
    getLoginData() {
      getLoginData(this.loginForm.username, this.loginForm.password).then(
        (res) => {
          if (res.meta.status === 400) {
            return this.$message({
              message: res.meta.msg,
              type: 'error',
            })
          }

          this.$message({
            message: res.meta.msg,
            type: 'success',
          })
          sessionStorage.setItem('token', res.data.token)
          this.$router.push('/home')
        }
      )
    },
  },
}
</script>

<style scoped>
.login-form {
  position: absolute;
  bottom: -10px;
  width: 100%;
  padding: 25px;
  box-sizing: border-box;
}
.btns {
  display: flex;
  justify-content: space-between;
}
</style>
